import os
import ftplib


class UploadToNasHelper:
    def __init__(self, host, username, password):
        self.__serverRootPath = None
        self.__host = host
        self.__username = username
        self.__password = password

    def set_upload_root(self, rootPath):
        self.__serverRootPath = rootPath

    def upload_folder(self, routeName, uploadPath):
        ftpObj = ftplib.FTP(self.__host)
        ftpObj.login(self.__username, self.__password)
        path = self.__serverRootPath
        ftpObj.cwd(path.decode("utf-8").encode("gbk"))

        for route in routeName:
            name = route.decode("utf-8").encode("gbk")
            if not route in ftpObj.nlst():
                ftpObj.mkd(name)
            ftpObj.cwd(name)

        for (filePath, dirs, files) in os.walk(uploadPath):
            for file in files:
                relativePath = os.path.join(filePath, file)
                with open(relativePath, "rb") as tempFile:
                    ftpObj.storbinary("STOR " + file, tempFile, 1024)
        ftpObj.quit()

    def upload_file(self, routeName, uploadFilePath):
        ftpObj = ftplib.FTP(self.__host)
        ftpObj.login(self.__username, self.__password)
        path = self.__serverRootPath
        ftpObj.cwd(path.decode("utf-8").encode("gbk"))

        for route in routeName:
            name = route.decode("utf-8").encode("gbk")
            if not route in ftpObj.nlst():
                ftpObj.mkd(name)
            ftpObj.cwd(name)

        with open(uploadFilePath, "rb") as tempFile:
            ftpObj.storbinary("STOR " + os.path.split(uploadFilePath)[1], tempFile, 1024)
        ftpObj.quit()
